<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-17
 * Time: 23:24
 */

namespace plugin\csauto\app\service;


use plugin\csauto\app\model\DownloaderModel;
use plugin\csauto\app\model\TorrentListModel;
use plugin\csauto\app\model\TorrentTaskModel;
use plugin\csauto\app\utils\TorrentDownloader;
use support\Db;


class TaskWorkService
{
//    private static $maxTaskLimit = 3;

    /**
     * 批量为多个下载器分配任务
     * @param array $downloaderIds 下载器ID数组
     * @param int $maxTasksPerDownloader 每个下载器最多分配的任务数（0表示尽可能多）
     * @return array 返回分配结果统计
     */
    public static function batchAssignTasks(array $downloaderIds, $maxTasksPerDownloader = 0)
    {
        $stats = [
            'total_assigned' => 0,
            'successful' => 0,
            'failed' => 0,
            'details' => []
        ];

        foreach ($downloaderIds as $downloaderId) {
            $downloaderStats = [
                'downloader_id' => $downloaderId,
                'assigned' => 0,
                'attempts' => 0
            ];

            // 获取该下载器可以接受的任务数量
            $model = DownloaderModel::where('id', $downloaderId)->first();
            if (!$model) {
                $downloaderStats['error'] = '下载器不存在';
                $stats['details'][] = $downloaderStats;
                continue;
            }

            $availableSlots = LoadBalancerService::getAvailableTaskSlots($model);
            
            // 确定要分配的任务数量
            $tasksToAssign = $availableSlots;
            if ($maxTasksPerDownloader > 0) {
                $tasksToAssign = min($tasksToAssign, $maxTasksPerDownloader);
            }

            // 尝试为该下载器分配多个任务
            for ($i = 0; $i < $tasksToAssign; $i++) {
                $downloaderStats['attempts']++;
                $result = self::assignTasks($downloaderId);
                
                if ($result === true || $result !== false) {
                    $downloaderStats['assigned']++;
                    $stats['successful']++;
                } else {
                    $stats['failed']++;
                    // 如果分配失败，可能是没有待分配的任务了，跳出循环
                    break;
                }
            }

            $stats['total_assigned'] += $downloaderStats['assigned'];
            $stats['details'][] = $downloaderStats;
            
            addlog('批量任务分配', "下载器ID：{$downloaderId}, 尝试：{$downloaderStats['attempts']}, 成功：{$downloaderStats['assigned']}");
        }

        return $stats;
    }

    /**
     * Created by 无所谓已
     * Date: 2025-08-17
     * Time: 23:58
     * assignTasks
     * 为下载器分配任务
     *
     * @param $downloaderId
     */
    public static function assignTasks($downloaderId)
    {
        $model = DownloaderModel::where('id', $downloaderId)->first();
        if (!$model) return false;
        /*检查一下已有的任务信息*/
        $taskCount = TorrentTaskModel::where('downloader_id', $downloaderId)->where('status', 1)->count();
        if ($taskCount >= $model->getEffectiveTaskLimit()) return false;
        /*任务不足。开始抓取任务（考虑下载器的任务种子大小范围）*/
        $torrentData = null;
        $minSizeGb = intval($model->task_torrent_min_size ?? 0);
        $maxSizeGb = intval($model->task_torrent_max_size ?? 0);

        if ($minSizeGb <= 0 && $maxSizeGb <= 0) {
            // 未设置范围，沿用原有逻辑
            $torrentData = TorrentListModel::where('torrents_status', 1)
                ->orderBy('created_at')
                ->first();
        } else {
            // 已设置范围，筛选满足范围的最早任务
            $candidates = TorrentListModel::where('torrents_status', 1)
                ->orderBy('created_at')
                ->limit(100)
                ->get();
            foreach ($candidates as $candidate) {
                $sizeGb = convertToGB($candidate->torrents_size);
                if ($minSizeGb > 0 && $sizeGb < $minSizeGb) {
                    continue;
                }
                if ($maxSizeGb > 0 && $sizeGb > $maxSizeGb) {
                    continue;
                }
                $torrentData = $candidate;
                break;
            }
            if (!$torrentData) {
                addlog('下载器分配', "下载器ID：{$downloaderId}, 未找到满足体积范围的候选任务(min={$minSizeGb}GB,max={$maxSizeGb}GB)");
                return false;
            }
        }
        $torrentTaskSpace = 0;
        if (!$torrentData) return false;
        $torrentTaskSpace += convertToGB($torrentData->torrents_size);

        $torrentTaskData = TorrentTaskModel::where('downloader_id', $downloaderId)->where('status', '>=', 1)->where('status', '<', 99)->where('down_status', '>', 0)->get();
        foreach ($torrentTaskData as $taskItem) {
            $torrentItem = TorrentListService::getTorrentListData($taskItem->site_id, $taskItem->torrent_id);
            if ($torrentItem) {
                $torrentTaskSpace += convertToGB($torrentItem->torrents_size);
            }
        }
        addlog('下载器分配', "下载器ID：{$downloaderId}, 预计容量：{$torrentTaskSpace},设计容量：{$model->task_size}");
        if ($torrentTaskSpace > $model->task_size) return false;

        /*存在待处理的资源*/
//        $filePath = '/torrent';
//        if (!is_dir($filePath)) {
//            mkdir($filePath, 0777, true);
//        }
        $torrent_path = false;
        try {
            $downloader = new TorrentDownloader('/torrents/', 30, true);
            $result = $downloader->download($torrentData->torrent_url);
            switch ($result['http_code']) {
                case 404:
                case 299:
                    $torrentData->torrents_status = 2;/*将任务进行分配*/
                    $torrentData->save();
                    break;
                default:
                    $torrent_path = $result['path'];
                    break;
            }

//            echo "文件名: " .  . "\n";

            // 检查文件内容
//            $content = file_get_contents($result['path']);
//            echo "文件前100字符: " . substr($content, 0, 100) . "\n";
        } catch (\Exception $e) {
            echo "错误: " . $e->getMessage() . "\n";
            $torrentData->created_at = date('Y-m-d H:i:s');/*将任务进行分配*/
            $torrentData->save();
            return false;
        }
//        return true;
        if ($torrent_path) {
            if (empty($torrentData->torrents_hash)) {
                /*重新更新hash值*/
                $torrentData->torrents_hash = getTorrentHash($torrent_path);
                $torrentData->save();
            }
            DB::beginTransaction();
            try {
                /*开始下载种子到置顶的文件夹中*/
                // ..业务处理略...
                $torrentTaskModel = new TorrentTaskModel;
                $torrentTaskModel->downloader_id = $downloaderId;
                $torrentTaskModel->site_id = $torrentData->site_id;
                $torrentTaskModel->torrent_id = $torrentData->torrent_id;
                $torrentTaskModel->torrent_hash = $torrentData->torrents_hash;
                $torrentTaskModel->torrent_path = $torrent_path;
                $torrentTaskModel->status = 1;
                $torrentTaskModel->down_status = 0;
                $torrentTaskModel->save();
                $torrentData->torrents_status = 2;/*将任务进行分配*/
                $torrentData->save();
                Db::commit();
            } catch (\Throwable $exception) {
                Db::rollBack();
            }
        } else {
            $torrentData->torrents_status = 2;/*将任务进行分配*/
            $torrentData->save();
        }
    }

}